package enumandlambda;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author shkstart
 * @create 2022-12-11-13:54
 */
public class ABADemo2 {
    private static AtomicStampedReference<Integer> money =
            new AtomicStampedReference<>(100, 0);

    public static void main(String[] args) throws InterruptedException {

        //第一次点击转账按钮（-50）
        Thread t1 = new Thread(() -> {
            int old_money = money.getReference();//余额
            int version = money.getStamp();//版本号
            //执行花费2S
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            money.compareAndSet(100,
                    old_money - 50,
                    version,
                    version + 1);
        });
        t1.start();

        //第2次点击转账按钮（-50）【不小心点击的，因为第一次点击之后没反应，所有不小心又点一次】
        Thread t2 = new Thread(() -> {
            //执行花费2S
            int old_money = money.getReference();
            int version = money.getStamp();
            money.compareAndSet(100,
                    old_money - 50,
                    version,
                    version+1);
        });
        t2.start();

        //给账户+50
        Thread t3 = new Thread(() -> {
            //执行花费1S
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            int old_money = money.getReference();
            int version = money.getStamp();
            money.compareAndSet(old_money,
                    old_money + 50,
                    version,
                    version+1);
        });
        t3.start();

        t1.join();
        t2.join();
        t3.join();

        System.out.println(money.getReference());

    }
}
